package cj.web.sc.controllers;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import cj.utils.Constants;
import cj.utils.DateUtils;
import cj.utils.ExportExcel;
import cj.utils.ReadConfigProperties;
import cj.utils.ReturnUUID;
import cj.utils.sc.KDNiaoUtil;
import cj.web.admin.domain.UserInfo;
import cj.web.constants.MemuEnum;
import cj.web.constants.PayStatusEnum;
import cj.web.constants.PayWayEnum;
import cj.web.constants.SCIsInvoiceEnum;
import cj.web.constants.SCOrderStatusEnum;
import cj.web.constants.SCShipperCodeEnum;
import cj.web.login.controllers.BaseController;
import cj.web.sc.dao.SCOrderDAO;
import cj.web.sc.dao.SCSellerDAO;
import cj.web.sc.domain.SCOrder;
import cj.web.sc.domain.SCSeller;

@Path("/order")
public class SCOrderController extends BaseController {

	private static Logger logger = Logger.getLogger(SCOrderController.class
			.getName());
	
	private final String[] headers = { "订单号", "商家名称", "订单详情", "订单总价", "收件人", "收件人电话", "收件人地址",
			"留言", "快递单号", "订单状态", "支付单号", "支付方式","支付时间" };

	@Autowired
	private SCOrderDAO orderDao;
	@Autowired
	private SCSellerDAO sellerDao;

	@Get("show")
	public String show(Model model, SCOrder order, HttpServletRequest request) {
		model.add("PayWayEnum", EnumSet.allOf(PayWayEnum.class));
		model.add("InvoiceEnum", EnumSet.allOf(SCIsInvoiceEnum.class));
		model.add("StatusEnum", EnumSet.allOf(SCOrderStatusEnum.class));
		model.add("ShipperEnum", EnumSet.allOf(SCShipperCodeEnum.class));
		model.add("MemuEnum", MemuEnum.scorder);
		return "/views/sc/orderList.vm";
	}

	@Post("list")
	public String list(Model model, SCOrder order, HttpServletRequest request) {
		UserInfo user = returnSessionObj(request);
		String acount = user.getAccount();
		int userId = user.getId();
		SCSeller seller = sellerDao.queryByUserInfoId(userId);

		if (seller != null) {
			order.setSellerId(seller.getId());
		}

		if (Constants.ADMIN.equals(acount)) { // admin账户可看到所有的
			order.setSellerId(-1);
		}

		List<SCOrder> objs = orderDao.queryBySellerId(order);
		int size = orderDao.sizeBySellerId(order);

		JSONObject jo = new JSONObject();
		jo.put("data", objs);
		jo.put("draw", order.getDraw());
		jo.put("recordsTotal", size);
		jo.put("recordsFiltered", size);
		return "@" + jo.toString();
	}

	@Get("output")
	public void output(Model model, SCOrder order,@Param("status")int status,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String sheetName = "商城订单";
		String title = URLEncoder.encode(sheetName, "UTF-8"); // 进行转码，使其支持中文文件名
		response.setContentType("application/vnd.ms-excel"); // 生成提示信息
		response.setHeader("content-disposition", "attachment;filename="
				+ title + DateUtils.getNowTime(DateUtils.DATE_FULL_STR1)+ ".xls");
		OutputStream fOut = response.getOutputStream();

		List<Map> dataset = null;
		ExportExcel<SCOrder> ex = new ExportExcel<SCOrder>();

		
		String[] fields = { "orderNo", "sellerName","itemDetails","discntPrice",
				"receiverName", "receiverPhone", "receiverAddress",
				"memo", "expressBill", "status", "wxTradeNo", "payWay","payAt" };

		UserInfo user = returnSessionObj(request);
		String acount = user.getAccount();
		int userId = user.getId();
		SCSeller seller = sellerDao.queryByUserInfoId(userId);
		if (seller != null) {
			order.setSellerId(seller.getId());
		}
		if (Constants.ADMIN.equals(acount)) { // admin账户可看到所有的
			order.setSellerId(-1);
		}
		order.setStatus(status);
		dataset = orderDao.outputBySellerId(order);

		for (Map map : dataset) {
			for (Object key : map.keySet()) {
				if(null == map.get(key)){
					map.put(key, "");
				}
			}
			/*String expressCom = SCShipperCodeEnum.getName(map.get("expressCom").toString());
			map.put("expressCom", expressCom);*/
			String strStatus = map.get("status").toString();
			strStatus = "".equals(strStatus) ? "" : SCOrderStatusEnum.getName(Integer.parseInt(strStatus));
			map.put("status", strStatus);
			
			String strPayWay = map.get("payWay").toString();
			strPayWay = "".equals(strPayWay) ? "" : PayWayEnum.getName(Integer.parseInt(strPayWay));
			map.put("payWay", strPayWay);
		}
		ex.exportExcelWithStrCellStyle(sheetName, headers, fields, dataset, fOut,
				DateUtils.DATE_FULL_STR);
		//更新导出状态
		orderDao.updateOutputBySellerId(order);
	}
	
	@Get("edit")
	public String edit(Model model, @Param("id") int id,
			HttpServletRequest request) {
		SCOrder obj = orderDao.queryById(id);
		model.add("obj", obj);
		model.add("MemuEnum", MemuEnum.scorder);
		model.add("ShipperEnum", EnumSet.allOf(SCShipperCodeEnum.class));
		return "/views/sc/orderEdit.vm";
	}

	@Post("update")
	public String update(Model model, SCOrder order, HttpServletRequest request) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);

		String acount = returnSessionObj(request).getAccount();
		order.setUpdateUser(acount);
		order.setStatus(SCOrderStatusEnum.posted.getValue());// 订单状态已发货

		try {
			orderDao.update(order);
		} catch (Exception e) {
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		return "@" + jo.toString();
	}

	@Get("chgXprBill")
	public String chgXprBill(Model model, @Param("id") int id,
			HttpServletRequest request) {
		SCOrder obj = orderDao.queryById(id);
		model.add("obj", obj);
		model.add("MemuEnum", MemuEnum.scorder);
		model.add("ShipperEnum", EnumSet.allOf(SCShipperCodeEnum.class));
		return "/views/sc/orderChgXpr.vm";
	}

	@Post("chgXpr")
	public String chgXpr(Model model, SCOrder order, HttpServletRequest request) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);

		String acount = returnSessionObj(request).getAccount();
		order.setUpdateUser(acount);

		try {
			orderDao.chgXprBill(order);
		} catch (Exception e) {
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		return "@" + jo.toString();
	}

	@Get("logist")
	public String logist(Model model, @Param("id") int id) throws Exception {
		SCOrder order = orderDao.queryById(id);
		if (order != null) {
			String expressCom = order.getExpressCom();
			String expressBill = order.getExpressBill();

			model.add("expressName", SCShipperCodeEnum.getName(expressCom));
			model.add("expressBill", expressBill);

			KDNiaoUtil api = new KDNiaoUtil();
			String result = api.getOrderTracesByJson(expressCom, expressBill);

			JSONObject jo = new JSONObject().fromObject(result);
			// 查询成功
			Boolean success = jo.getBoolean("Success");
			if (success) {
				Object reaObj = jo.get("Reason");
				if (reaObj == null) {
					// 物流路线
					JSONArray jslis = jo.getJSONArray("Traces");
					List<Map> list = JSONArray.toList(jslis, Map.class);// 过时方法
					Collections.reverse(list);

					model.add("list", list);
				} else {
					model.add("reason", reaObj.toString());
				}
			} else {
				Object reaObj = jo.get("Reason");
				if (reaObj != null) {
					model.add("reason", reaObj.toString());
				}
			}

		}

		model.add("MemuEnum", MemuEnum.scorder);
		return "/views/sc/logistics.vm";
	}

	@Get("finish")
	// 买家已收货
	public String finish(Model model, @Param("id") int id) {
		SCOrder order = orderDao.queryById(id);
		if (order != null) {
			orderDao.setStatus(id, SCOrderStatusEnum.finish.getValue());
		}

		return "r:show";
	}

	@Get("delete")
	// 买家已收货
	public String delete(Model model, @Param("id") int id,
			HttpServletRequest request) {
		SCOrder order = orderDao.queryById(id);
		if (order != null) {
			String acount = returnSessionObj(request).getAccount();
			order.setUpdateUser(acount);
			orderDao.delete(order);
		}

		return "r:show";
	}
	
	@Post("xlsInput")
	public String xlsInput(Model model, @Param("xlsFile")MultipartFile xls) throws FileNotFoundException, IOException {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		// 判断文件是否为空  
		if (xls != null && !xls.isEmpty()) {
			String orgName = xls.getOriginalFilename();
			String ext =  ReturnUUID.getFileExt(orgName);
			if( ext != null && ext.equals(".xls")){
            	//文件保存路径  
            	String path = ReadConfigProperties.getValue("uploadFilePath");
            	//文件名
                String fileName =  ReturnUUID.getName(orgName);
                //转存文件  
                File tmpXls = new File(path+"/"+fileName);
                xls.transferTo(tmpXls);
                //处理excel文件
                jo = operateXls(tmpXls);
			}
			else{
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
				jo.put("returnCode", Constants.returnObj.returnCode.code_2); //文件不是excel
			}
        }
		else{
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			jo.put("returnCode", Constants.returnObj.returnCode.code_1);     //文件不存在
		}

		return "@" + jo.toString();
	}

	private JSONObject operateXls(File tmpXls) throws FileNotFoundException, IOException {
		JSONObject jo = new JSONObject();
		//获取工作簿
		HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(tmpXls));
		//获取sheet页
		HSSFSheet sheet = workbook.getSheetAt(0);
		
		//获取标题行
		HSSFRow titles = sheet.getRow(0);
		if(titles.getPhysicalNumberOfCells() != headers.length){
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			jo.put("returnCode", Constants.returnObj.returnCode.code_3);     //请按照订单导出的Excel导入数据
			return jo;
		}
		String wrongTitles = "",rightTitles="";
		for( int col= 0; col < titles.getPhysicalNumberOfCells(); col++ ){
			String title = titles.getCell(col).getStringCellValue();
			if(!title.equals(headers[col])){
				wrongTitles += title + " ";
				rightTitles += headers[col] + " ";
			}
		}
		if(!"".equals(wrongTitles)){
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			jo.put("returnCode", Constants.returnObj.returnCode.code_4);     //导入表表头错误
			jo.put("wrongTitles", wrongTitles);
			jo.put("rightTitles", rightTitles);
			return jo;
		}
		
		/*------判断订单中数据正确性 START------*/
		int rowNum = sheet.getLastRowNum();
		
		String orderNOReg = "\\d{20}";
		Pattern pattern = Pattern.compile(orderNOReg);
		String xpsReg = "\\d+";
		Pattern xpsPattern = Pattern.compile(xpsReg);
		
		String emptyOrderNOes="",notMatchOrderNOes="",
				notExistOrderNOes="";
		String emptyExpressBills="",notMatchExpressBills="";
		String orderNoes[] = new String[rowNum];
		String expressBills[] = new String[rowNum];
		for( int rowIndex = 1; rowIndex <= rowNum; rowIndex++ ){
			HSSFRow row = sheet.getRow(rowIndex);
			
			HSSFCell orderNoCell = row.getCell(0);
			String orderNo = "";
			if(orderNoCell != null){
				orderNoCell.setCellType(Cell.CELL_TYPE_STRING);
				orderNo = orderNoCell.getStringCellValue();
			}
			if(orderNo != null && !"".equals(orderNo)){
				Matcher orderNOMatcher = pattern.matcher(orderNo);
				if(orderNOMatcher.matches()){
					int flag = orderDao.getOrderByNO(orderNo);
					if(flag > 0){
						orderNoes[rowIndex-1] = orderNo;
					}
					else{
						notExistOrderNOes += orderNo + "，";
					}
				}
				else{
					notMatchOrderNOes += orderNo +  "，";
				}
			}
			else{
				emptyOrderNOes += (rowIndex + 1) + "行A列，";
			}
			
			HSSFCell xpsBillCell = row.getCell(8);
			String expressBill = "";
			if(xpsBillCell != null){
				xpsBillCell.setCellType(Cell.CELL_TYPE_STRING);
				expressBill = xpsBillCell.getStringCellValue();
			}
			if(expressBill !=null && !"".equals(expressBill)){
				Matcher xpsMatcher = xpsPattern.matcher(expressBill);
				if(xpsMatcher.matches()){
					expressBills[rowIndex-1] = expressBill;
				}
				else{
					notMatchExpressBills += expressBill + "，";
				}
				
			}
			else{
				emptyExpressBills += (rowIndex + 1) + "行I列，";
			}
		}
		
		boolean isReturn = false;
		if(!"".equals(emptyOrderNOes)){
			jo.put("emptyOrderNOes", emptyOrderNOes);
			isReturn = true;
		}
		if(!"".equals(notMatchOrderNOes)){
			jo.put("notMatchOrderNOes", notMatchOrderNOes);
			isReturn = true;
		}
		if(!"".equals(notExistOrderNOes)){
			jo.put("notExistOrderNOes", notExistOrderNOes);
			isReturn = true;
		}
		if(!"".equals(emptyExpressBills)){
			jo.put("emptyExpressBills", emptyExpressBills);
			isReturn = true;
		}
		if(!"".equals(notMatchExpressBills)){
			jo.put("notMatchExpressBills", notMatchExpressBills);
			isReturn = true;
		}
		if(isReturn){
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			jo.put("returnCode", Constants.returnObj.returnCode.code_5);     //导入表数据错误
			return jo;
		}
		/*------判断订单中数据正确性 END------*/
		
		//更新状态
		for(int i = 0; i < orderNoes.length; i++){
			//orderDao.updateOrderByInput(orderNoes[i], expressBills[i], SCShipperCodeEnum.CJKD.getValue());
			orderDao.updateOrderByInput(orderNoes[i], expressBills[i]);
		}
		
		return jo;
	}

}
